package com.algorithm.string_and_array;

import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

@Slf4j
public class ArraySolutionLC07 {
    public int[][] merge(int[][] intervals) {
        // 根据第一个元素排序
        Arrays.sort(intervals, new Comparator<int[]>() {
            @Override
            public int compare(int[] o1, int[] o2) {
                if (o1[0] == o2[0]) {
                    return o1[1] - o2[1];
                }
                return o1[0] - o2[0];
            }
        });
        // 双指针发合并区间
        int j = 0;
        int i = 1;
        while (j < intervals.length && i < intervals.length) {
            if (intervals[j][1] >= intervals[i][0] && intervals[j][1] < intervals[i][1]) {
                intervals[j][1] = intervals[i][1];
                intervals[i][0] = -1;
                intervals[i][1] = -1;
            } else if (intervals[j][1] >= intervals[i][1]) {
                intervals[i][0] = -1;
                intervals[i][1] = -1;
            } else {
                j = i;
            }
            i++;
        }
        // 将合并后的挑出来
        List<int[]> list = new ArrayList<>();
        for (int k = 0; k < intervals.length; k++) {
            if (intervals[k][1] != -1) {
                list.add(intervals[k]);
            }
        }

        return list.toArray(new int[list.size()][2]);
    }

    @Test
    public void test() {
        int[][] aa = {{1, 4}, {2, 3}};
        int[][] merge = merge(aa);
        log.info("this is {}", merge.length);
    }
}
